from django.shortcuts import render
from django.http import HttpResponse

from . import models


# def index(request):
#     return HttpResponse('hello world!')

# def index(request):
#     return render(request, 'index.html')

# def index(request):
#     return render(request, 'blog/index.html', {'hello': 'hello blog!'})

# def index(request):
#     article = models.Article.objects.get(pk=1)
#     return render(request, 'blog/index.html', {'article': article})

def index(request):
    article_list = models.Article.objects.all()
    return render(request, 'blog/index.html', {'article_list': article_list})


def article_detail(request, article_id):
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/article_detail.html', {'article': article})


def article_edit(request, article_id):
    if str(article_id) == '0':
        return render(request, 'blog/article_edit.html')
    article = models.Article.objects.get(pk=article_id)
    return render(request, 'blog/article_edit.html', {'article': article})


def edit_action(request):
    title = request.POST['title']
    content = request.POST['content']
    article_id = request.POST['article_id']
    if article_id == '0':
        models.Article.objects.create(title=title, content=content)
        article_list = models.Article.objects.all()
        return render(request, 'blog/index.html', {'article_list': article_list})

    article = models.Article.objects.get(pk=article_id)
    article.title = title
    article.content = content
    article.save()
    return render(request, 'blog/article_detail.html', {'article': article})
